export class Event {
	events = {};
	constructor() {
		this.events = {};
	}

	on(eventName, fn) {
		this.createEvent(eventName).push(fn);
	}

	once(eventName, fn) {
		const once = () => {
			this.off(eventName, once);
			fn();
		};
		this.createEvent(eventName).push(fn);
	}

	off(eventName, fn) {
		const eventList = this.createEvent(eventName);
		const index = eventList.findIndex(fn);
		if (index > -1) {
			eventList.splice(index, 1);
		}
	}

	emit(eventName, data = {}) {
		this.createEvent(eventName).forEach((fn) => {
			if (fn) fn(data);
		});
	}

	createEvent(eventName) {
		if (!this.events[eventName]) {
			this.events[eventName] = [];
		}
		return this.events[eventName];
	}

	destroy() {
		this.events = {};
	}
}
